
//商家列表
var starttime=""; //开始时间
var endtime=""; //结束时间
var pagesize=10;
var pageindex=1;
var sortfild = ""; //排序的关键字
var sortway = ""; //排序：升序、降序
var ttname = "商家列表";
var uid_department = getCookie("admin_role");
var uid_encryptid = getCookie("uid_encryptid");
$(function() {
	//排序 
	$(".list_sort_tab").click(function(){
		 sortfild=$(this).attr("value"); 
		if($(this).find("i").hasClass("icon_downs")){
			$(this).find("i").removeClass("icon_downs");
			$(this).find("i").addClass("icon_ups");
			sortway="asc";
		}else{
			$(this).find("i").removeClass("icon_ups");
			$(this).find("i").addClass("icon_downs");
			 sortway="desc";
		}
		 //必须要，否则排序则不能调用该方法  使用该句，当点击排序，就同时点击了 第一页的按钮，自动调用分页的效果，
        $("#first_button").click();
	});
	
	
	 //下拉框
    $(document).on('click', ".my_select_ul li", function () {
        $(this).parent().siblings("div").find("span").html($(this).text());
        $(this).parent().siblings("div").find("span").attr("value", $(this).attr("value"));
        if($(this).parent().siblings("div").find("span").hasClass("business_type_select")){
            if($(this).text() == "全部"){
                $(".business_type_select").text("商户类型");
            }
        }else if($(this).parent().siblings("div").find("span").hasClass("review_select")){
            if($(this).text() == "全部"){
                $(".review_select").text("审核状态");
            }
        }
      
        //获取数据
        $("#first_button").click();
    })
	
	
	//悬浮显示 当宽度小于 文字宽度时，则鼠标移到该内容时，悬浮显示，将文字全部显示出来
	 $(document).on("mouseover",".show_tips",function(){
        if($(this).width()>$(this).parent().width()){
	            layer.tips($(this).html(), $(this), {
	                tips: [1, '#3595CC'],
	                time: 0
	            })
	        }
	});
    $(document).on("mouseout",".show_tips",function(){
        layer.closeAll('tips');
   	});

    /*切换搜索条件*/
    $("#conditional_search").find("li").click(function () {
        $("#search_name").text($(this).text());
        $(this).find("a").attr('value');
        $("#search_name").attr('value', $(this).find("a").attr('name'));
    });
    
   	//时间选择
	timesearch();
	var today=new Date();
	startDate=endDate=today.format('yyyy-MM-dd');
	starttime=endtime=startDate;
	$("#date1").html(startDate+" - "+endDate);

	$(".select_time1 li ").click(function(){
		$(".select_time1 li").removeClass("blue_color");
		$(this).addClass("blue_color");
		var time=$(this).attr("name");
		if(time=="0"){
			startDate=endDate=today.format('yyyy-MM-dd');
		}else if(time=="1"){
			startDate=endDate=new Date(today.getFullYear(),today.getMonth(),today.getDate()-1).format('yyyy-MM-dd');
		}else if(time=="7"){
			startDate=new Date(today.getFullYear(),today.getMonth(),today.getDate()-6).format('yyyy-MM-dd');
			endDate=today.format('yyyy-MM-dd');
		}else if(time=="30"){
			startDate=new Date(today.getFullYear(),today.getMonth(),today.getDate()-29).format('yyyy-MM-dd');
			endDate=today.format('yyyy-MM-dd');
		}
		starttime=startDate;
		endtime=endDate;
		$("#date1").html(startDate+" - "+endDate);
		if(time==""){
			starttime="";
			endtime="";
		}
		//获取数据
		$("#first_button").click();
	})

    //搜索回车事件
    $('#conditional_searchinput').bind('keypress',function(event){
        if(event.keyCode == 13) {
            addgoods();
        }
    });
	
	getData();
	
})

//搜索
function addgoods() {
    $("#first_button").click();
}

function getData(){
	getlist();
}

//数据列表
function getlist() {
    var pagesize = $("#selectPageSize1").text();
    var pageindex = $("#currentPage").text();
    var searchval=$("#conditional_searchinput").val().trim(); //搜索内容
    var field=$("#search_name").attr("value"); //搜索字段
    var reviewStatus = $("#review_select_name").attr("value");//审核状态下拉
    var business_type = $("#business_type_name").attr("value");//商户类型下拉

    var layLoad=layer.load(2);
    $("#biuuu_city_list").empty();
    $.post('/businesinfo/getbusinessinfolist',
        {
            "pagesize": pagesize,
            "pageindex": pageindex,
            "starttime": starttime,
            "endtime": endtime,
            "searchval": searchval,
            "searchkey": field,
            "sortway": sortway,
            "sortfild": sortfild,
            "business_type": business_type,
            "reviewStatus": reviewStatus
        }, function (value) {
        layer.close(layLoad);
        if(value.status==0 && value.msg == "ok"){
            var list=value.list;
            var pagecount=value.pagecount;
            var recordcount=value.recordcount;
            $("#totalSize").html(recordcount);
            $("#totalPage").html(pagecount);
            if(list.length==0){
                $("#biuuu_city_list").prepend("<tr class=\"iframe_tr iframe_bg\"><td colspan=\"12\" style=\"width:1126px;text-align:center;\">暂无数据</td></tr>");
            }else{
                var htm="";
                for(var i=0;i<list.length;i++){
                    if(list[i].business_encryptId == uid_encryptid || uid_department == "2"){
                        htm+="<tr>";
                        htm+="<td><span class='show_tips'>"+(list[i].business_name==null?"":list[i].business_name)+"</span></td>";
                        htm+="<td><span class='show_tips'>"+(list[i].CompanyName == null ?"":list[i].CompanyName)+"</span></td>";
                        htm+="<td><span class='show_tips'>"+(list[i].business_Legal == null ?"":list[i].business_Legal)+"</span></td>";
                        htm+="<td><span class='show_tips'>"+(list[i].business_tel == null ?"":list[i].business_tel)+"</span></td>";
                        htm+="<td><span class='show_tips'>"+(list[i].business_license == null ?"":'<img src="'+list[i].business_license+'?x-oss-process=style/tuImgStyle" layer-src="'+list[i].business_license+'" >')+"</span ></td>";
                        htm+="<td><span class='show_tips'>"+(list[i].business_Credit == null ?"":list[i].business_Credit)+"</span></td>";
                        htm+="<td><span class='show_tips'>"+(list[i].business_type == null ?"":getBusinessTypeName(list[i].business_type))+"</span></td>";
                        htm+="<td><span class='show_tips'>"+(list[i].business_create == null ?"":list[i].business_create)+"</span></td>";
                        htm+="<td><span class='show_tips'>"+(list[i].business_state == null ?"":getstateName(list[i].business_state))+"</span></td>";
                        htm+="<td><span class='show_tips'>"+(list[i].remarks == null ?"":list[i].remarks)+"</span></td>";

                        htm+="<td class='td-manage'>";

                        if(list[i].business_state == "1"){
                            //只有审核通过状态下
                            if(list[i].sec_encryptId == "0" && list[i].farm_encryptId != ""  && ( list[i].business_state == "1" || uid_department == "2" || list[i].business_encryptId == uid_encryptid)){
                                htm +="<a class=\"customerdetail\" onclick=\"question_details('"+list[i].business_encryptId+"','"+list[i].farm_encryptId+"','"+list[i].business_type+"')\">详情</a>";
                            }else if(list[i].sec_encryptId != "" && list[i].farm_encryptId == "0" && ( list[i].business_state == "1" || uid_department == "2" || list[i].business_encryptId == uid_encryptid)){
                                htm +="<a class=\"customerdetail\" onclick=\"question_details('"+list[i].business_encryptId+"','"+list[i].sec_encryptId+"','"+list[i].business_type+"')\">详情</a>";
                            }
                        }

                        if(list[i].business_encryptId == uid_encryptid || uid_department == "2"){
                            htm += "<a href=\"javascript:void(0)\" onclick=\"question_del('"+list[i].business_encryptId+"','"+list[i].farm_encryptId+"','"+list[i].sec_encryptId+"')\">删除</a></div>";
                        }

                        htm += "</td>";

                        htm+="</tr>";
                    }

                }
                $("#biuuu_city_list").html(htm);

            }
        }else{
            if(value.msg==null||value.msg==""){
                layer.alert("接口出现错误！", {icon: 2})
            }else{
                layer.alert(value.msg, {icon: 2})
            }
        }
    })
}

//根据审核状态码，返回审核值
function getstateName(state) {
	if(state != "" && state!= null){
		if(state == 0){
			return "未审核";
		}else if(state == 1){
            return "已通过";
        }else if(state == 2){
            return "已拒绝";
        }
	}else {
		return "";
	}
}
//根据商户类型id，返回商户类型名称
function getBusinessTypeName(business_type) {
    if (business_type != "" && business_type!=null){
        if(business_type == "1"){
            return "农家乐";
        }else if(business_type == "2"){
            return "旅游景区";
        }
    }else {
        return "";
    }
}



//农家乐商家信息修改——编辑
function farm_question_edit() {
    ComOpenWin(1, "编辑", "1000px", 'auto', $("#FarmMerchantupgradeWin"), 1);
}

//景区商家信息修改——编辑
function farm_question_edit() {
    ComOpenWin(1, "编辑", "1000px", 'auto', $("#TourMerchantupgradeWin"), 1);
}


/*删除*/
function question_del(business_encryptId,farm_encryptId,sec_encryptId) {
    layer.confirm('确认要删除吗,删除后该商家的所有的相关信息也会被删除，恢复到普通用户状态？', function(index) {
        var ii = layer.load(2);
        $.post('/businesinfo/delbusinessinfo', {"business_encryptId": business_encryptId,"farm_encryptId":farm_encryptId,"sec_encryptId":sec_encryptId}, function (data) {
            layer.close(ii);
            if (data.status == 0 && data.msg == 'ok') {
                layer.msg("操作成功！",{time:2000,icon:1});
                $("#first_button").click();
                mclose();
            } else {
                if(data.msg==null||data.msg==""){
                    layer.alert("接口出现错误！", {icon: 2})
                }else{
                    layer.alert(data.msg, {icon: 2})
                }
            }
        })
    });
}

//点击图片，进行放大
$(document).on("click", "#biuuu_city_list tr td", function () {
    var url = $(this).find("img").attr("layer-src");
    if(url != "" && url != undefined && url != "undefined"){
        seePicture(url);
    }
})

//图片放大
function seePicture(url) {
    var url = url.split(",");
    var photos = new Array();
    for (var i = 0; i < url.length; i++) {
        photos.push({"alt": "图片" + (1 + i), "pid": "", "src": url[i], "thumb": ""});
    }
    var json = {"title": "素材", "id": "", "start": 0, "data": photos};
    layer.photos({
        photos: json,
        area: "[auto,auto]",
        skin: "layer_photos"
        , shift: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
    });
}

/**************************************详情页面跳转-start*******************************************************/

//点击详情 - 跳转商家详情信息页面
function question_details(business_encryptId,shop_encryptId,businessTypeid) {
    setcookie("business_encryptId",business_encryptId,1,"/");//商家加密id
    setcookie("shop_encryptId",shop_encryptId,1,"/"); //店铺加密id
    if(businessTypeid == "1"){
        var size = "merchant/merchant_information_new.html".length;
        window.parent.addTab_father("农家乐商家详情", "merchant/merchant_information_new.html", size);
    }else if(businessTypeid == "2"){
        var size = "tourist/tour_info_new.html".length;
        window.parent.addTab_father("景区商家详情", "tourist/tour_info_new.html", size);
    }
}















/**************************************公共时间方法-start*******************************************************/
//时间选择控制器
function timesearch(){
	
	  layui.use('laydate', function () {
        var laydate = layui.laydate;

        //日期范围
        laydate.render({
            elem: '#date1'
            ,range: true
            ,startDate:new Date().format('yyyy-MM-dd')
            ,endDate:new Date().format('yyyy-MM-dd')
            ,btns: ['confirm']
            ,ready: function(date){
              //默认控件打开的时候调用一下向左点击的事件，则显示的日期范围为左边为上个月月份，右边为当月月份
              $(".laydate-main-list-0 .laydate-prev-m").click();
          	}
            ,max: time()//设置最大日期为当前日期时间
            ,done: function (value, date, endDate) { //选择好日期的回调
                startDate=starttime= value.substring(0, 10);
                endDate=endtime= value.substring(13, 23);
                pageindex = 1;
                $("#date1").html(startDate+" - "+endDate);
                $(".select_time1 li").removeClass("blue_color");
                //获取数据
				$("#first_button").click();
            }
        });
    });

}
/**
 * 获取当前时间
 * @returns {String}
 */
function time(){
	var myDate = new Date(); 
	var year=myDate.getFullYear();
	var month=parseInt(myDate.getMonth()+1);
	var day=myDate.getDate();
	var timedate=year+"-"+month+"-"+day;
	return timedate;
};
function time1(){
	var myDate = new Date(); 
	var year=myDate.getFullYear();
	var month=parseInt(myDate.getMonth()+1);
	var day=parseInt(myDate.getDate()-1);
	var timedate=year+"-"+month+"-"+day;
	return timedate;
};
/**
 * 当前时间段
 */
function timequantum(n){
	var myDate = new Date(); 
	var year=myDate.getFullYear();
	var month=parseInt(myDate.getMonth()+1);
	var day=myDate.getDate();
	if(n>day){
		if(month>1){
			month=parseInt(month-1);
		}else{
			year=parseInt(year-1);
		}
	}else{
		day=parseInt(day-n);
	}
	var timedate=year+"-"+month+"-"+day;
	return timedate;
}
function DateDiff(sDate1, sDate2) {  //sDate1和sDate2是yyyy-MM-dd格式
    var aDate, oDate1, oDate2, iDays;
    aDate = sDate1.split("-");
    oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]);  //转换为yyyy-MM-dd格式
    aDate = sDate2.split("-");
    oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]);
    iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24); //把相差的毫秒数转换为天数
 
    return iDays;  //返回相差天数
}
Date.prototype.format =function(format){
	var o = {
		"M+" : this.getMonth()+1, //month
		"d+" : this.getDate(), //day
		"h+" : this.getHours(), //hour
		"m+" : this.getMinutes(), //minute
		"s+" : this.getSeconds(), //second
		"q+" : Math.floor((this.getMonth()+3)/3), //quarter
		"S" : this.getMilliseconds() //millisecond
	}
	if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
	(this.getFullYear()+"").substr(4- RegExp.$1.length));
	for(var k in o)if(new RegExp("("+ k +")").test(format))
	format = format.replace(RegExp.$1,
	RegExp.$1.length==1? o[k] :
	("00"+ o[k]).substr((""+ o[k]).length));
	return format;
}
